<?php
include 'includes/functions.php';
echo db_connect();

$section_id = $_GET['sid']; if (!$section_id) $section_id = $_POST['section_id'];
$action = $_GET['action']; if (!$action) $action = $_POST['action'];

if ($_GET['delete']) {
	
	if (!$result = mysql_query("DELETE FROM documentation_sections WHERE section_id = '$section_id'")) DIE(mysql_error());
	
	// TODO: make it look up other sections (if any) following this one in the same 
	// what seems to be happening: they are deleting all details within a section which
	// makes that section non-existant but does not re-order the following items;
	// we could trap for this and tell them to move it to the end of the list before
	// delting the last item. This makes it hard to do by accident as well.
	
	
	header("location:index.php?msg=d");
}

if($_GET['reorder']) {
  $section_id = $_GET['sid'];
  $type = $_GET['type'];
  $direction = $_GET['direction'];
  if ($direction == 'down') { $oper = '>'; $dir = 'ASC';}
  if ($direction == 'up') { $oper = '<'; $dir = 'DESC';}

 	if ($type == 'section'){
	      $old_ids = array(); $new_ids = array(); 
			
	 		// get source section num, chapter id   
			$lookup_sql = "SELECT `section_num`, documentation_chapter_id FROM documentation_sections WHERE section_id = '$section_id'"; //echo $lookup_sql;
		   $lookup_result=mysql_query($lookup_sql); $lookup_row=mysql_fetch_array($lookup_result); //echo $lookup_sql;  			  
			$lookup_section_num=$lookup_row[0];
			$lookup_chapter_id=$lookup_row[1]; 
			
			// get target section num  
			$lookup_sql1 = "SELECT `section_num` FROM documentation_sections 
			WHERE `section_num` $oper $lookup_section_num 
			AND documentation_chapter_id = '$lookup_chapter_id' 
			ORDER BY `section_num` $dir LIMIT 1"; 
			///echo $lookup_sql1;  
			$lookup_result1=mysql_query($lookup_sql1); 
			if (!$lookup_row1=mysql_fetch_array($lookup_result1)) { header("location:index.php?s=$section_id"); exit;}

			$lookup_new_section_num = $lookup_row1[0]; //echo "||$lookup_new_section_num||";
			
		 
			
			// get ids of details with new section num
			
			$sqlW = "SELECT section_id from documentation_sections WHERE documentation_chapter_id = '$lookup_chapter_id' AND section_num = '$lookup_new_section_num'";
			$resultW = mysql_query($sqlW); 
			while ($rowW = mysql_fetch_array($resultW)   ) { $new_ids[] = $rowW[0]; } 
			
			
			  // get ids of details with same section num

				$sqlX = "SELECT section_id from documentation_sections WHERE documentation_chapter_id = '$lookup_chapter_id' AND section_num = '$lookup_section_num'";
				$resultX = mysql_query($sqlX); 
				while ($rowX = mysql_fetch_array($resultX)   ) { $old_ids[] = $rowX[0]; }    
				 
				
				foreach ($old_ids as $key => $val) {
					// set source records to target records' section num
					$sql = "UPDATE documentation_sections SET `section_num` = '$lookup_new_section_num' WHERE section_id = '$val'"; //echo "$sql <br>";
					if (!$result = mysql_query($sql)) DIE('error'. $sql); 
				}
				
            foreach ($new_ids as $key => $val) {
	         	// set target records to source record's old section num
					$sql = "UPDATE documentation_sections SET `section_num` = '$lookup_section_num' WHERE section_id = '$val'"; //echo "$sql <br>";
			  		if (!$result = mysql_query($sql)) DIE('error'. $sql);        
				}
	
	
	
	}
	
	if ($type == 'chapter'){
	   $chapter_id = $_GET['cid'];
	//source   
	$lookup_sql = "SELECT `order` FROM documentation_chapters WHERE documentation_chapter_id = '$chapter_id'"; //echo $lookup_sql;
	   $lookup_result=mysql_query($lookup_sql); $lookup_row=mysql_fetch_array($lookup_result); $lookup_order=$lookup_row[0];
	// target   
	$lookup_sql1 = "SELECT documentation_chapter_id, `order` FROM documentation_chapters WHERE `order` $oper $lookup_order ORDER BY `order` $dir LIMIT 1";   $lookup_result1=mysql_query($lookup_sql1); $lookup_row1=mysql_fetch_array($lookup_result1); 
		$lookup_id1=$lookup_row1[0];
		$lookup_order1=$lookup_row1[1];
	
		// set target record to source record's old order
		$sql = "UPDATE documentation_chapters SET `order` = '$lookup_order' WHERE documentation_chapter_id = '$lookup_id1'"; //echo "$sql ::";
		if (!$result = mysql_query($sql)) DIE('error'. $sql);
	
		// set source record to target record's order
		$sql = "UPDATE documentation_chapters SET `order` = '$lookup_order1' WHERE documentation_chapter_id = '$chapter_id'"; //echo "$sql ::";
		if (!$result = mysql_query($sql)) DIE('error'. $sql);
	}
	
	if ($type == 'detail'){
	  
		 // get source section num, chapter id, order   
			$lookup_sql = "SELECT `section_num`, documentation_chapter_id, `order` FROM documentation_sections WHERE section_id = '$section_id'"; //echo $lookup_sql;
		   $lookup_result=mysql_query($lookup_sql); $lookup_row=mysql_fetch_array($lookup_result); //echo $lookup_sql;  			  
			$lookup_section_num=$lookup_row[0];
			$lookup_chapter_id=$lookup_row[1];
			$lookup_order=$lookup_row[2]; 
			
			
			// get target id, order based on section_num, chapter_id, order -/+ 1 
			$lookup_sql1 = "SELECT `section_id`, `order` FROM documentation_sections 
			WHERE `order` $oper $lookup_order 
			AND documentation_chapter_id = '$lookup_chapter_id'
			AND section_num = '$lookup_section_num' 
			ORDER BY `order` $dir LIMIT 1"; 
			///echo $lookup_sql1;  
			$lookup_result1=mysql_query($lookup_sql1); 
			if (!$lookup_row1=mysql_fetch_array($lookup_result1)) { header("location:index.php?s=$section_id"); exit;}

			$lookup_new_section_id = $lookup_row1[0];
			$lookup_new_order = $lookup_row1[1]; 
		 
			// set target record to source record's old order
			$sql = "UPDATE documentation_sections SET `order` = '$lookup_order' WHERE section_id = '$lookup_new_section_id'"; //echo "$sql ::";
			if (!$result = mysql_query($sql)) DIE('error'. $sql);

			// set source record to target record's order
			$sql = "UPDATE documentation_sections SET `order` = '$lookup_new_order' WHERE section_id = '$section_id'"; //echo "$sql ::";
			if (!$result = mysql_query($sql)) DIE('error'. $sql);
	
	}
	
  header("location:index.php?s=$section_id"); 
}

if($_POST['posted']) {
	# print_r($_POST); exit;
	
	$detail_title = addslashes ($_POST['detail_title']);
	$body = addslashes ($_POST['form']['info1']);
	$notes = addslashes ($_POST['notes']);
	$known_issues = addslashes ($_POST['known_issues']);
	$status = $_POST['status'];
	$last_editor = addslashes ($_POST['last_editor']);
	setcookie("editor_initials", $last_editor);
	
	if ($action == 'new') {
	   $posted_section_id = $_POST['section_id'];
		$lookup = mysql_query("SELECT section_num, documentation_chapter_id, (`order` + 1), title FROM documentation_sections WHERE section_id = '$posted_section_id'");
		if (!$lookup_row = mysql_fetch_array($lookup)) DIE("lookup error");
		$lookup_section_num = $lookup_row[0];
		$lookup_cid = $lookup_row[1];  
		$lookup_order = $lookup_row[2];
		$lookup_title = $lookup_row[3];
		$sql = "INSERT INTO documentation_sections (documentation_chapter_id, section_num, detail_title, `order`, body,title,modified_ts,notes,status,last_editor,known_issues) VALUES ('$lookup_cid','$lookup_section_num','$detail_title','$lookup_order', '$body', '$lookup_title',NOW(),'$notes','$status','$last_editor','$known_issues')";  
		
	} else {
	 
    	$sql = "UPDATE documentation_sections SET detail_title='$detail_title', body = '$body',modified_ts = NOW(),notes = '$notes', status = '$status', last_editor = '$last_editor', known_issues = '$known_issues' WHERE section_id = '$section_id'"; //echo $sql;
		
	}
	
   if  (!mysql_query ($sql)) {
	DIE(mysql_error().$sql); 
	} else {
		echo "<script type='text/javascript' charset='utf-8'>
		window.location = 'index.php?s=$section_id'; 
		</script>";
	}
	
} else {



if ($action != 'new') 
{
	$sql1 = "SELECT * FROM documentation_sections WHERE section_id = '$section_id'"; //echo $sql1;
	$result1 = mysql_query($sql1);

	$row1 = mysql_fetch_array($result1);
	$detail_title= stripslashes($row1['detail_title']);
	$body=stripslashes($row1['body']);
	$order=$row1['order'];
	$modified_ts=$row1['modified_ts'];
	
	$notes=stripslashes($row1['notes']);
	$known_issues = stripslashes($row1['known_issues']);
	
	$last_editor=$row1['last_editor']; // We don't display this cuz we want re-entry each edit
	$status=$row1['status']; 
}

# BUILD STATUS DROP DOWN
# $statuses arr defined in functions
$statusDD = "<select name = 'status' id='status'>\n";
foreach($statuses as $key=> $val) {
 if ($status == $key) { $slektd = " selected='selected'"; } else { $slektd = ""; }
 $statusDD .= "<option id='status-$key' value='$key'$slektd>$val</option>\n";
}
$statusDD .= "</select>\n";

?>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>    
<link rel="stylesheet" href="/documentation/includes/wysiwyg/jquery.rte.css" type="text/css" />
<link rel="stylesheet" href="/documentation/css/app_styles.css" type="text/css" />     
<title>ClientTracker Manual</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" charset="utf-8">
	$(document).ready(function() {
		$('#mainform').submit(function() {
			if ( $('#last_editor').val() == '') {
				alert("Please enter your initials before saving.");
				$('#last_editor').focus();
				return false;
			}
			
		});
		
		$('#delete').click(function() {
			if (confirm ('Are you sure you want to delete this detail? This cannot be undone.') ){    
				document.location = "edit.php?sid=<?=$section_id?>&delete=1";
			}
			
		});
		
	});
 

  
</script>
</head>

<body>
<div id="main" style="width:800px;">
<form action="edit.php" method="POST" name="form1" id="mainform">
<input type="hidden" name="posted" value="1" id="posted">
<input type="hidden" name="section_id" value="<?=$section_id?>" id="posted">
<input type="hidden" name="action" value="<?=$action?>" id="posted">
<p>
<div id='edit_box' style='width:640px;'>
Status: <?=$statusDD?>
<div style='float:right;text-align:right;'>Last modified: <strong><?=$modified_ts?></strong>
<br>by <strong><?=$last_editor?></strong></div></br> 
<input type="text" name="detail_title" class="detail_title" cols="65" value="<?=$detail_title?>" id="title" size="60">


</div>
</p>
 <p>
	<textarea name="form[info1]" cols="100" rows="10"  class="rte2" method="post" action="#" style="background-color:white;"><?=$body?></textarea>
 </p>

<br>
<br>

<div id='edit_box' style='background-color:#83b34b'>Your Initials: <input type="text" name="last_editor" value="<?php echo $_COOKIE['editor_initials']; ?>" id="last_editor" size="2"></div><br> 
<div id='edit_box' style='background-color:#B1BFF8'>Notes: <textarea name="notes" id="notes" class="notes_input"><?=$notes?></textarea> </div>
<div id='edit_box' style='background-color:#F8C37E'>Known<br>Issues: <textarea name="known_issues" id="known_issues" class="notes_input"><?=$known_issues?></textarea> </div>
<br>

<br><br>  
<input type="submit" name="submit" value="Save Changes" id="some_name"> <input type="button" name="submit" value="Cancel" onClick="window.location='index.php?s=<?=$section_id?>';" id="some_name"> 
</form>
<br>

<input type="button" value="Delete this detail" name='delete' id='delete'>  


<script type="text/javascript" src="/documentation/includes/wysiwyg/jquery.rte.js"></script>
<script type="text/javascript" src="/documentation/includes/wysiwyg/jquery.rte.tb.js"></script>
<script type="text/javascript" src="/documentation/includes/wysiwyg/jquery.ocupload-1.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	var arr = $('.rte1').rte({
		css: ['css/styles.css'],
		controls_rte: rte_toolbar,
		controls_html: html_toolbar
	});

	$('.rte2').rte({
		css: ['css/styles.css'],
		width: 650,
		height: 250,
		controls_rte: rte_toolbar,
		controls_html: html_toolbar
	}, arr);
});
</script>

</body>
</html>

<?php 
  }
?>